package com.ydw.datahub.utils;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.ydw.datahub.properties.MongoProperties;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * Created by admin on 2018/9/10.
 */
public class MongoUtils {

    static Logger logger= LoggerFactory.getLogger(MongoUtils.class);

    /**
     * 获取mongo认证客户端
     * @param mongoProperties
     * @param list
     * @return
     */
    public static MongoClient getMongoClient(MongoProperties mongoProperties, List<MongoCredential> list){
        return new MongoClient(new ServerAddress(mongoProperties.getUrl(),mongoProperties.getPort()) ,list);
    }

    /**
     *
     * @param mongoClient
     * @param dbName
     * @param collectionsName
     * @param result
     */
    public static void getCount(MongoClient mongoClient, String dbName, List<String> collectionsName, HashMap<String,String> result){
        MongoDatabase db = mongoClient.getDatabase(dbName);
        collectionsName.stream().forEach(x->{
            MongoCollection<Document> collection = db.getCollection(x);
            long count = collection.count();
            logger.info("数据库:{}集合:{}:数量{}",dbName,x,count);
            result.put(x,count+"");
        });
    }

    public static void getResult(MongoProperties mongoProperties, HashMap<String,String> result){
        List<String> books = Arrays.asList("books", "units");
        List<String> categories = Arrays.asList("phases", "types","publishers","topics");
        List<String> resources = Arrays.asList("resources");
        HashMap<String, List<String>> stringListHashMap = new HashMap<>();
        stringListHashMap.put("books",books);
        stringListHashMap.put("categories",categories);
        stringListHashMap.put("resources",resources);
        stringListHashMap.entrySet().stream().forEach(x->{
            MongoCredential credential = MongoCredential.createCredential(mongoProperties.getUserName(), x.getKey(),mongoProperties.getPassword().toCharArray());
            MongoClient mongoClient = getMongoClient(mongoProperties,Arrays.asList(credential));
            getCount(mongoClient,x.getKey(),x.getValue(),result);
            mongoClient.close();
        });
    }


}
